let socketConnected = false;


import { IP } from "./req"
let url = `ws://${IP}:8081`;


// 登录函数
let timer_login = null

// 监听WebSocket连接打开
uni.onSocketOpen(function (res) {
  console.log('WebSocket连接已打开');
  socketConnected = true;
});
export const initWebsocket = () => {
  uni.connectSocket({
    url: url,
    success: function (res) {
      console.log('WebSocket连接成功');
    },
    fail: function (err) {
      console.error('WebSocket连接失败:', err);
      // 尝试重新连接
      setTimeout(() => {
        uni.connectSocket({
          url: url,
        });
      }, 5000);
    }
  });




  // 监听WebSocket关闭
  uni.onSocketClose(function (res) {
    console.log('WebSocket连接已关闭');
    socketConnected = false;
    // 尝试重新连接
    setTimeout(() => {
      uni.connectSocket({
        url: url,
      });
    }, 5000);
  });

  // 监听WebSocket错误
  uni.onSocketError(function (err) {
    console.error('WebSocket错误:', err);
    socketConnected = false;
    // 尝试重新连接
    setTimeout(() => {
      uni.connectSocket({
        url: url,
      });
    }, 5000);
  });
}

export const login = (uid) => {
  if (!socketConnected) {
    timer_login = setTimeout(() => {
      login(uid)
    }, 100)
    return
  }
  uni.sendSocketMessage({
    data: JSON.stringify({
      event: 'login',
      uid: uid
    }),
    success: function (res) {
    },
    fail: function (err) {
      throw new Error('登录消息发送失败:', err);
    }
  });
};
// 登录函数
export const sendMsg = (sendData) => {
  if (!socketConnected) {
    return
  }
  uni.sendSocketMessage({
    data: JSON.stringify({
      event: 'message',
      sendData
    }),
    success: function (res) {
    },
    fail: function (err) {
      throw new Error('消息发送失败:', err);
    }
  });
};
export const closeSocket = () => {
  if (!socketConnected) {
    return
  }
  uni.sendSocketMessage({
    data: JSON.stringify({
      event: 'logout',
    }),
    success: function (res) {
    },
    fail: function (err) {
      throw new Error('消息发送失败:', err);
    }
  });
}